import initShaders from "./initShaders.js"
import { vertexShader,fragmentShader } from "./shader.js"   
import { mat4 } from './gl_matrix/esm/index.js'
import { initVertexBuffers } from './cube_data.js'

//获取DOM元素
let canvas = document.getElementById("canvas")
//获取webgl上下文
let gl = canvas.getContext("webgl")

//初始化着色器
initShaders(gl,vertexShader,fragmentShader)
//初始化顶点数据
initVertexBuffers(gl)
//获取模型矩阵
let u_modelMatrix = gl.getUniformLocation(gl.program, 'u_modelMatrix')
//旋转矩阵
let deg = 0
let rotateMatrix = mat4.create()
//平移矩阵
let translateMatrix = mat4.create()
mat4.fromTranslation(translateMatrix, [0, 0, -0.5])
//缩放矩阵
let scaleMatrix = mat4.create()
mat4.fromScaling(scaleMatrix, [1, 1, 1])
//设置摄像机坐标
let u_viewMatrix = gl.getUniformLocation(gl.program, 'u_viewMatrix')
let viewMatrix = mat4.create()
mat4.lookAt(viewMatrix, [0, 0, 5], [0, 0, 0], [0, 1, 0])
gl.uniformMatrix4fv(u_viewMatrix, false, viewMatrix)
//透视投影
let u_projectionMatrix = gl.getUniformLocation(gl.program, 'u_projectionMatrix')
let perspectiveMatrix = mat4.create()
mat4.perspective(perspectiveMatrix, 45 * Math.PI / 180, canvas.width / canvas.height, 0.01, 100)
gl.uniformMatrix4fv(u_projectionMatrix, false, perspectiveMatrix)
//方向光
let u_lightingDirection = gl.getUniformLocation(gl.program, 'u_lightDirection')
let lightingDirection = [0, 1, 1]
gl.uniform3fv(u_lightingDirection, lightingDirection)
//光颜色
let u_lightColor = gl.getUniformLocation(gl.program, 'u_lightColor')
let lightColor = [1, 1, 1]
gl.uniform3fv(u_lightColor, lightColor)

let time = Date.now()
function tick() {
    let newTime = Date.now()
    let deltaTime = newTime - time
    time = newTime

    deg += deltaTime / 50

    mat4.fromRotation(rotateMatrix, deg / 180 * Math.PI, [1, 1, 0])
    // //复合矩阵
    let modelMatrix=mat4.create()
    mat4.multiply(modelMatrix,rotateMatrix, scaleMatrix)
    mat4.multiply(modelMatrix, translateMatrix, modelMatrix)    
    gl.uniformMatrix4fv(u_modelMatrix, false, modelMatrix)
    draw(gl)

    requestAnimationFrame(tick)
}
tick()

function draw(gl) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
    gl.enable(gl.DEPTH_TEST)

    for (let i = 0; i < 24; i += 4) {
        gl.drawArrays(gl.TRIANGLE_FAN, i, 4)
    }
}